package org.fluidripple.file;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.fluidripple.socket.stickhalf.DelimiterBasedFrameDecoderImpl;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
@Slf4j
public class DeviceDataMappedFile {

    //每个文件100M的数据
    private final int fileSize =  1*1024*1024*100;//1 * 1024 * 1024 * 20 ;
    public static final String baseDirPath = "/data/device/files";
    private String dirPath = baseDirPath+"/%s/%s";
    private MappedFile mappedFile;
    private ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(20000);
    private String device;
    private SyncAppendMessage syncAppendMessage;

    public DeviceDataMappedFile(String device) {
        this.device = device;
        this.syncAppendMessage = new SyncAppendMessage();
    }

    public MappedFile newMappedFile(){
        String format = DateFormatUtils.format(new Date(), device+"-yyyy年MM月dd日 HH时mm分ss秒")+".txt";
        String fileName = String.format(dirPath, device,format);
        mappedFile = new MappedFile(fileName,fileSize);
        return mappedFile;
    }

    public void appendMessage(ByteBuf buf){

        String hexDump = ByteBufUtil.hexDump(buf);
        if (hexDump.trim().isEmpty()){
            return;
        }
        try {
            queue.offer(hexDump,1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private class SyncAppendMessage implements Runnable{

        private Thread thread;

        public SyncAppendMessage() {
            log.info("启动 {} 设备线程，准备写入数据",DeviceDataMappedFile.this.device);
            thread = new Thread(this);
            thread.start();
        }

        @Override
        public void run() {
            for (;;){
                try {
                    String message = queue.take();
                    LocalDateTime localDateTime = LocalDateTime.now();
                    String date = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
                    message = DelimiterBasedFrameDecoderImpl.DELIMITER+message +" " +date +"\r\n";
                    if (mappedFile == null || mappedFile.isFull(message.getBytes(StandardCharsets.UTF_8).length)){
                        newMappedFile();
                    }
                    mappedFile.appendMessage(message);
                } catch (InterruptedException e) {
                    log.info("系统异常=>",e);
                }
            }
        }
    }
}
